package com.example.demo.controller;

import com.example.demo.Services.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * ClassName:IndexController
 * Package:com.controller
 * Description:
 *
 * @date:2019/12/12 15:41
 * @author:
 */
@Controller
@RequestMapping(value = "/")
public class IndexController {

    @RequestMapping(value = "login")
    public String login(Model model){
        model.addAttribute("name","Jonou");
        return "login";
    }

    @RequestMapping(value = "tologin")
    public String tologin(Model model){

        return "tologin";
    }

    @RequestMapping(value = "user/add")
    public String addUser(Model model){
        return "user/adduser";
    }

    @RequestMapping(value = "user/update")
    public String updateUser(Model model){
        return "user/updateuser";
    }

    @RequestMapping(value = "toError")
    public String error(Model model){
        model.addAttribute("msg","没有权限");
        return "error";
    }


    @RequestMapping(value = "index")
    public String index(String name,String password,Model model){
        /**
         * 使用shiro 的认证功能
         */
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(name,password);


        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
//            e.printStackTrace();
            model.addAttribute("msg","用户名不存在");
            return "tologin";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "tologin";
        }

        return "redirect:login";
    }


}

